package com.dhcc.utils.map;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.dhcc.utils.Operator;
import com.dhcc.utils.OperatorException;
import com.dhcc.utils.__Convert;
import com.dhcc.utils.__String;

/**
 * 转换map中的值
 * @author hibean@qq.com 2017年6月28日
 *
 */
public class ConvertValueOperator implements Operator<Map> {

	static final Map<String, Converter> converters = new HashMap<String, Converter>();
	static{
		converters.put("Integer", new Converter(){
			@Override
			public Object convert(Object from) {
				return __Convert.toInt(from);
			}
		});
		converters.put("Double", new Converter(){
			@Override
			public Object convert(Object from) {
				return __Convert.toDouble(from);
			}
		});
		converters.put("Long", new Converter(){
			@Override
			public Object convert(Object from) {
				return __Convert.toLong(from);
			}
		});
		converters.put("Float", new Converter(){
			@Override
			public Object convert(Object from) {
				return __Convert.toFloat(from);
			}
		});
		converters.put("String", new Converter(){
			@Override
			public Object convert(Object from) {
				return from==null?null:from.toString();
			}
		});
		converters.put("Boolean", new Converter(){
			@Override
			public Object convert(Object from) {
				return __Convert.toBoolean(from);
			}
		});
		converters.put("Short", new Converter(){
			@Override
			public Object convert(Object from) {
				return __Convert.toShort(from);
			}
		});
		converters.put("Byte", new Converter(){
			@Override
			public Object convert(Object from) {
				return __Convert.toByte(from);
			}
		});
		converters.put("Char", new Converter(){
			@Override
			public Object convert(Object from) {
				return __Convert.toChar(from);
			}
		});
	}
	private static interface Converter{
		Object convert(Object from);
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Object invoke(String operator, Map first, Object[] args) {
		String to = __String.op("after", operator, "To");
		Map result = new HashMap();
		Set<Entry> set = first.entrySet();
		
		if(converters.containsKey(to)){
			Converter converter = converters.get(to);
			for (Entry entry : set) {
				Object key = entry.getKey();
				Object value = entry.getValue();
				result.put(key, converter.convert(value));
			}
		}else{
			throw new OperatorException("不支持转换为 "+to);
		}
		return result;
	}
}
